<template>
    <ul class="v3DialogList">
        <li v-for="dialog in dialogList" :key="dialog._sign_" :id="dialog._sign_">
            <RenderFormDialog v-bind="dialog"/>
        </li>
    </ul>
</template>
<script lang="jsx" setup name="v3Dialog">
/* 弹框组件，基于v3Form组件。增强获取到表单数据后的下一步处理功能 */
import v3Form from './v3Form.vue'
import { ElMessage } from 'element-plus'
import { isNotEmpty, isHtml, parseTemplate } from '@/utils/tools'
import { usePageInfo } from '@/hooks/pageInfo'
import { ref, reactive } from 'vue'
import V3Table from './v3Table.vue'
const emit = defineEmits(['up']);
const { pageInfo } = usePageInfo()
let dialogVisible = reactive({})
let dialogFormRef = reactive([])
let dialogTableRef = reactive([])
const dialogList = reactive({})
const props = defineProps({
    schema: {
        type: Object,
        default: () => {}
    }
})
let schema = reactive({
    "width": 700,
    "title": '表单',
    "inline": false,
    ...props.schema
})

/* dialog 私有方法 */
const privateFn = {
    close: (config, data = {}, id) => {
        if (!id) return
        // debugger
        // console.log('v3Dialog--close--',id, dialogFormRef[id])
        /* 关闭dialog时，清空表单数据 */
        dialogFormRef[id].value.reset()
        document.getElementById(id)?.remove()
        dialogVisible[id] = false
        delete dialogList[id]
    },
    open: (obj = {}, data = {}) => {
        console.log('v3Dialog--open--', obj, data, pageInfo)
        // let dialog
        /* 打开dialog时，生成时间戳，确保唯一性 */
        // if (!Object.keys(dialogList)?.includes(obj?.id)) obj.id = new Date().getTime()
        if (!obj?._sign_) obj._sign_ = new Date().getTime()
        // if (!isBoolean(dialogVisible[obj.id])) {
        const dialog = {
            _sign_: obj._sign_,
            formData: obj?.formData || data,// 编辑时，表单数据默认追加
            extraData: {...pageInfo},
            type: obj?.dialogType || 'form',
            tableData: data?.tableData || [],
            schema: {
                index: obj?.index,// tab页的排序
                title: obj?.title || obj?.label,
                width: obj?.width || schema.width,
                inline: obj?.inline || schema.inline,
                items: obj?.fields  || schema.items,
                isClosedRemoveDom: obj?.isClosedRemoveDom || true,
                operations: obj?.operations,
                headTip: obj?.headTip,
                footTip: obj?.footTip
            },
            // idx: dialogList.length ? dialogList.length - 1 : 0,
        }
        if (!dialog.formData['dialogId']) dialog.formData['dialogId'] = obj._sign_
        dialogVisible[obj._sign_] = true
        Object.assign(dialogList, {[obj._sign_]: dialog})
        return dialog
    },
    commit(config, data) {
        // 请求逻辑统一放在operation组件, fetch 方法 处理了请求成功后的配置 */
        emit('up', {index: schema.index, ...config, 'actOn': 'operation', 'rangeFn': 'fetch'}, data, res => {
            // fn && fn(config, data).then(res => {
                console.log('v3Dialog--commit--', res)
                const { successCb, errorCb } = config?.request
                if (res.isError) {
                    (errorCb && privateFn[errorCb]) ? privateFn[errorCb](config, data) : isNotEmpty(res) && emit('fetch', {"widgetName": 'operation',...res})
                    return
                } else {
                    // 请求成功后，关闭弹框
                    privateFn.close({}, data, data.dialogId)
                    /* successCb && emit('up', {index: schema.index, ...successCb}, fn => {
                        fn && fn(successCb)
                    }) */
                }
            // })
        })
    },
    getData(a, b, id) {
        return dialogFormRef[id].value.getFormData()
    }
}
/* dialog处理表单提交方法 */
const handleForm = (config, data = {}, i) => {
    // console.log('v3Dialog--handleForm--', config, data)
    const { rangeFn, request = {}, isCloseDialog } = config
    if (privateFn[rangeFn]) {
        const info = privateFn[rangeFn](config, data, i)
        Object.assign(data, info)
        // console.log(`v3Dialog--${privateFn}--${rangeFn}--`, info)
        if (config.next) {
            emit('up', {index: schema.index, ...config.next}, data, result => {
                // const result = handle && handle(config.next, data)
                console.log('v3Dialog--handleForm--result--', result)
            })
        }
    } else {
        emit('up', {index: schema.index, ...config}, {}, data => {
            // const data = fn && fn()
            // console.log('v3Dialog--handleForm--data--', data)
            if (config.next) {
                emit('up', {index: schema.index, ...config.next}, data, result => {
                    // const result = handle && handle(config.next, data)
                    console.log('v3Dialog--handleForm--result--', result)
                })
            }
        })
    }
    if (isCloseDialog && data.dialogId) {
        privateFn.close(config, data, data.dialogId)
    }
}
const handleFormEvent = (config, data, id) => {
    // console.log('v3Dialog--handleFormEvent--', config, data)
    emit('event', config, data, id)
}
const closed = (obj = {}) => {
    console.log('v3Dialog--closed--', obj)
    const dom = document.getElementById(obj._sign_)
    // privateFn.close(obj.schema, obj.formData, obj._sign_)
    if (obj?.schema.isClosedRemoveDom && dom) {
        dom.remove()
        delete dialogList[obj._sign_]
    }
}
// console.log('v3Dialog-schema-', schema)
defineExpose({ "open": privateFn.open, "close": privateFn.close, "commit": privateFn.commit, "getData": privateFn.getData })
const RenderFormDialog = (obj) => {
    {
        const { schema, formData, _sign_:id, extraData, type, tableData } = obj
        console.log('v3Dialog--RenderFormDialog--', obj, id)
        const data = { selectedSize: formData.length, formData, ...schema, ...extraData}
        dialogFormRef[id] = ref()
        return (
            <el-dialog v-model={dialogVisible[id]} onClose={privateFn.close} title={schema.title} onclosed={closed(obj)} class={'v3Dialog'}>
                {
                    schema.headTip && !isHtml(schema.headTip) ? <p>{parseTemplate(schema.headTip, data)}</p>
                    : <div v-html={parseTemplate(schema.headTip, data)}></div>
                }
                {
                    type === 'table' ? <V3Table ref={dialogTableRef[id]} data={tableData} schema={schema} columns={schema.items} isAlone={true} isDailog={true} key={id}/>
                    : <v3Form ref={dialogFormRef[id]} model={ formData } schema={schema} key={id}
                    onSubmit={(c, d) => handleForm(c, d, id)} onEvent={(c, d) => handleFormEvent(c, d || formData, id)} isAlone={false} />
                }
                {
                    schema.footTip && !isHtml(schema.footTip) ? <p>{parseTemplate(schema.footTip, data)}</p>
                    : <div v-html={parseTemplate(schema.footTip, data)}></div>
                }
            </el-dialog>
        )
    }
}
</script>
<style>
.v3Dialog .el-dialog__body{
    max-height: 740px;
    overflow-y: auto;
}
</style>
